<template>
  <CompaniesList
    :companies="companies"
    :empty-text="$t('contacts::contact.no_companies_associated')"
  >
    <template #actions="{ company }">
      <IButtonIcon
        v-show="authorizeDissociate"
        v-i-tooltip.left="$t('contacts::company.dissociate')"
        icon="X"
        @click="$confirm(() => dissociateCompany(company.id))"
      />
    </template>

    <template #top-actions>
      <button
        v-if="showCreateButton"
        v-i-tooltip="$t('contacts::company.add')"
        type="button"
        class="ml-4 rounded border border-neutral-200 bg-white p-0.5 text-neutral-700 hover:bg-neutral-50 focus:outline-none dark:border-neutral-500 dark:bg-neutral-700 dark:text-neutral-100 dark:hover:bg-neutral-800"
        @click="$emit('create-requested')"
      >
        <Icon icon="Plus" class="h-4 w-4" />
      </button>
    </template>
  </CompaniesList>
</template>

<script setup>
import { inject } from 'vue'
import { useI18n } from 'vue-i18n'

import CompaniesList from './CompaniesList.vue'

defineProps({
  companies: { required: true, type: Array },
  contactId: { required: true, type: Number },
  authorizeDissociate: { required: true, type: Boolean },
  showCreateButton: { required: true, type: Boolean },
})

const emit = defineEmits(['dissociated', 'create-requested'])

const detachResourceAssociations = inject('detachResourceAssociations')

const { t } = useI18n()

async function dissociateCompany(id) {
  await detachResourceAssociations({ companies: [id] })

  emit('dissociated', id)

  Innoclapps.success(t('core::resource.dissociated'))
}
</script>
